package com.lagou.work.task01.oom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * tcp通信客户端
 */

public class SoketClientTest {

    private static Boolean flag = true;
    private static final int _1MB = 512 * 1024;
    private static char[] sendCharArr;

    /**
     * 构造client发送的msg，大小为1M
     */
    static {
        sendCharArr = new char[1*_1MB];
        for (int i = 0; i <sendCharArr.length ; i++) {
            sendCharArr[i] = 'a';
        }

    }
    public static void main(String[] args) throws InterruptedException {
        Socket socket = null;
        PrintStream ps = null;
        BufferedReader bufferedReader = null;
        Scanner sc = null;
        String msgServer = null;
        String eixtStr = null;
        try {
            socket = new Socket("localhost",8888);
            ps = new PrintStream(socket.getOutputStream());

            String str = String.valueOf(sendCharArr);
            sc = new Scanner(System.in);
            while(flag){
                System.out.println("请输入本次发送信息的大小(M)：");
                int size = sc.nextInt();
                String msg = null;
                for(int i =0; i < size; i++ ){
                    msg += str;
                }
                for (int i = 0; i < 50; i++) {
                    ps.println(msg);
                    System.out.println("客户端发送 "+size+"M 数据成功!!");
                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    msgServer = bufferedReader.readLine();
                    System.out.println(msgServer);
                    Thread.sleep(1000);
                }

                System.out.println("是否继续发送：yes/no ?");
                eixtStr = sc.next();
                if(!"yes".equals(eixtStr)){
                    ps.println("eixt");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close(socket, ps, bufferedReader, sc);
        }
    }

    /**
     * 关闭连接
     */
    public static void close(Socket socket, PrintStream ps, BufferedReader bufferedReader, Scanner sc){
        try {
            if(null != socket){
                socket.close();
            }
            if(null != ps){
                ps.close();
            }
            if(null != bufferedReader){
                bufferedReader.close();
            }
            if(null != sc){
                sc.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
